package com.imelite.qyh.util;

import com.alibaba.fastjson.JSONObject;
import com.imelite.qyh.enums.WechatEnum;
import com.imelite.qyh.factory.EliteCRMView_OrgUserFactory;
import com.imelite.qyh.model.EliteCRMView_OrgUser;
import com.jeecg.qywx.api.base.JwAccessTokenAPI;
import com.jeecg.qywx.api.core.common.AccessToken;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

public class BaseUserUtil{
    private static String corpid="wxaad2914913724470";

    public static String getAccessToken(HttpServletRequest request){
        String AgentId=request.getParameter("AgentId");
        System.out.println("AgentId="+AgentId);
        WechatEnum wechatEnum=WechatEnum.getThisByValue(AgentId);
        AccessToken accessToken=JwAccessTokenAPI.getAccessToken(corpid,wechatEnum.getLabel());
        return accessToken.getAccesstoken();
    }

    //获取微信UserId
    public static String getWxUserId(HttpServletRequest request){
        HttpSession session = request.getSession();
        String session_WxUserId = (String)session.getAttribute("EliteQYH_WxUserId");
        if(BaseStringUtil.isBlank(session_WxUserId)){
            String AccessToken=getAccessToken(request);
            String code=request.getParameter("code");
            String url="https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token="+AccessToken+"&code="+code;
            JSONObject jsonObject = com.jeecg.qywx.api.core.util.HttpUtil.sendGet(url);
            String UserId=jsonObject.getString("UserId");
            session.setAttribute("EliteQYH_WxUserId", UserId);
            session_WxUserId = (String)session.getAttribute("EliteQYH_WxUserId");
        }
        return session_WxUserId;
    }

    //只要获取User信息一定要经过微信验证获取到Openid
    public static EliteCRMView_OrgUser getUser(HttpServletRequest request){
        String session_WxUserId = getWxUserId(request);
        EliteCRMView_OrgUser user= EliteCRMView_OrgUserFactory.selectByWxcode(session_WxUserId);
        return user;
    }
}
